package com.guonima.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URI;

/**
 * @author : guonima
 * @create : 2017-10-28-21:36
 */
@Service
public class TestService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RestTemplate restNoBalancedTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    public String test(String name){
        return restTemplate.getForObject("http://eureka-client/test?name=" + name, String.class);
    }

    public String test2(String name){

        // 负载均衡选择一个服务实例进行调用
        ServiceInstance instance = this.loadBalancerClient.choose("eureka-client");
        URI uri = URI.create(String.format("http://%s:%s/test", instance.getHost(), instance.getPort()));

        logger.info("Target service uri = {}. ", uri.toString());

        return restNoBalancedTemplate.getForObject(uri + "?name=" + name, String.class);
    }

}
